package com.morningstar.system.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.morningstar.system.controller.entity.RoleMenu;
import com.morningstar.system.dao.entity.SysRoleMenu;
import com.morningstar.system.dao.mapper.SysRoleMenuMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色和菜单关联表 服务实现类
 * </p>
 *
 * @author yanglianshan
 * @since 2023-06-28
 */
@Slf4j
@Service
public class SysRoleMenuService extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> {

    @Resource
    private SysRoleMenuMapper roleMenuMapper;

    @Transactional
    public void setPermission(RoleMenu roleMenu) {
        Long roleId = roleMenu.getRoleId();
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        SysRoleMenu sysRoleMenu;
        List<SysRoleMenu> roleMenuList = new ArrayList<>();
        for (Long menuId : roleMenu.getChecked()) {
            sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setCheckType("1");
            roleMenuList.add(sysRoleMenu);
        }
        for (Long menuId : roleMenu.getHalfChecked()) {
            sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setCheckType("0");
            roleMenuList.add(sysRoleMenu);
        }
        this.saveBatch(roleMenuList);
    }
}
